package oauth.signpost.signature;

import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;

import oauth.signpost.OAuth;
import oauth.signpost.http.HttpParameters;
import oauth.signpost.http.HttpRequest;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;


/**
 * Writes to the HTTP Authorization header field.
 * 
 * @author Matthias Kaeppler
 */
public class BodySigningStrategy implements SigningStrategy {

    private static final long serialVersionUID = 1L;

    public String writeSignature(String signature, HttpRequest request,
            HttpParameters requestParameters) {
        StringBuilder sb = new StringBuilder();

        
        sb.append(OAuth.OAUTH_CONSUMER_KEY + "=");
        sb.append(requestParameters.getFirst(OAuth.OAUTH_CONSUMER_KEY,true));
        sb.append("&");
        
        sb.append(OAuth.OAUTH_NONCE + "=");
        sb.append(requestParameters.getFirst(OAuth.OAUTH_NONCE,true));
        sb.append("&");
        
        sb.append(OAuth.OAUTH_SIGNATURE + "=");
        sb.append(OAuth.percentEncode(signature));
        sb.append("&");
        
        sb.append(OAuth.OAUTH_SIGNATURE_METHOD + "=");
        sb.append(requestParameters.getFirst(OAuth.OAUTH_SIGNATURE_METHOD));
        sb.append("&");
        
        sb.append(OAuth.OAUTH_TIMESTAMP + "=");
        sb.append(requestParameters.getFirst(OAuth.OAUTH_TIMESTAMP));
        sb.append("&");
        
        sb.append(OAuth.OAUTH_VERSION + "=");
        sb.append(requestParameters.getFirst(OAuth.OAUTH_VERSION));
        sb.append("&");
                
        
        sb.append(OAuth.XAUTH_MODE + "=");
        sb.append(requestParameters.getFirst(OAuth.XAUTH_MODE,false));
        sb.append("&");
        
        sb.append(OAuth.XAUTH_PASSWORD + "=");
        sb.append(requestParameters.getFirst(OAuth.XAUTH_PASSWORD,false));
        sb.append("&");
        
        sb.append(OAuth.XAUTH_USERNAME + "=");
        sb.append(requestParameters.getFirst(OAuth.XAUTH_USERNAME,false));
        
        
        //String bodyString = URLEncoder.encode(strBuffer.toString(), "ISO-8859-1");
        String bodyString = sb.toString();
        
        try{
          StringEntity bodyEntity = new StringEntity(bodyString);
          OAuth.debugOut("Body", sb.toString());
          HttpPost post = (HttpPost)request.unwrap();
          post.setEntity(bodyEntity);        

          request.setHeader("Content-Type", "application/x-www-form-urlencoded");
        }
        catch(Exception e)
        {            
          return null;  
        }
               
        return bodyString;
    }

}
